package com.ibeeking.found.common.config.feign;

import com.ibeeking.found.common.constants.HeaderNounConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.SneakyThrows;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Optional;


/**
 * feign转发header参数
 *
 * @author langpf 2018/12/19
 */
@Configuration
public class FeignRequestInterceptor implements RequestInterceptor {

    public FeignRequestInterceptor() {
    }

    @SneakyThrows
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Map<String, String> context = ThreadContext.getContext();
        if (!CollectionUtils.isEmpty(context)) {
            for (Map.Entry<String, String> entry : context.entrySet()) {
                if (HeaderNounConstant.USER_NAME.equals(entry.getKey())) {
                    requestTemplate.header(entry.getKey(), URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.name()));
                } else {
                    requestTemplate.header(entry.getKey(), entry.getValue());
                }
            }
        } else if (null != attributes) {
            Optional.ofNullable(attributes.getRequest().getHeader(HeaderNounConstant.TENANT_ID)).ifPresent(tenantId -> requestTemplate.header(HeaderNounConstant.TENANT_ID, tenantId));
            Optional.ofNullable(attributes.getRequest().getHeader(HeaderNounConstant.INDUSTRY)).ifPresent(industry -> requestTemplate.header(HeaderNounConstant.INDUSTRY, industry));
            Optional.ofNullable(attributes.getRequest().getHeader(HeaderNounConstant.SHOP_ID)).ifPresent(shopId -> requestTemplate.header(HeaderNounConstant.SHOP_ID, shopId));
            requestTemplate.header(HeaderNounConstant.TRACE_ID, attributes.getRequest().getHeader(HeaderNounConstant.TRACE_ID));
            requestTemplate.header(HeaderNounConstant.LOGIN_SYSTEM, attributes.getRequest().getHeader(HeaderNounConstant.LOGIN_SYSTEM));
            requestTemplate.header(HeaderNounConstant.LOGIN_ROLE, attributes.getRequest().getHeader(HeaderNounConstant.LOGIN_ROLE));
            requestTemplate.header(HeaderNounConstant.USER_ID, attributes.getRequest().getHeader(HeaderNounConstant.USER_ID));
            Optional.ofNullable(attributes.getRequest().getHeader(HeaderNounConstant.USER_NAME)).ifPresent(userName -> requestTemplate.header(HeaderNounConstant.USER_NAME, userName));
        }
    }
}
